import { Context, Next } from 'koa'
import permissionService from '@/service/permission.service'
import { IPermissionTypes } from '@/types/permission.types'

class PermissionController {
  /**
   * 新增菜单
   * @param ctx 
   * @param next 
   * @returns 
   */
  public async create(ctx: Context, next: Next) {
    const permission = ctx.request.body as unknown as IPermissionTypes
    try {
      const res: any = await permissionService.create(permission)
      if (res.length) {
        ctx.body = {
          code: 200,
          success: true,
        }
        return
      }
      ctx.body = {
        code: 80001,
        msg: '添加失败'
      }
    } catch (e) {
      console.log(e)
      ctx.body = {
        code: 80001,
        msg: e.message || '系统异常'
      }
    }
  }

  /**
   * 修改菜单
   * @param ctx 
   * @param next 
   */
  public async edit(ctx: Context, next: Next) {
    const permission = ctx.request.body as unknown as IPermissionTypes
    try {
      const res = await permissionService.edit(permission)
      if (res.length) {
        ctx.body = {
          code: 200,
          success: true,
        }
        return
      }
      ctx.body = {
        code: 80001,
        msg: '添加失败'
      }
    } catch (e) {
      console.log(e)
      ctx.body = {
        code: 80001,
        msg: e.message || '系统异常'
      }
    }

  }

  /**
   * 删除菜单
   * @param ctx 
   * @param next 
   */
  public async delete(ctx: Context, next: Next) {
    const { id } = ctx.request.query
    try {
      const res = await permissionService.delete(Number(id) || -1)
      if (res.length) {
        ctx.body = {
          code: 200,
          success: true,
        }
        return
      }
      ctx.body = {
        code: 80001,
        msg: '删除失败'
      }
    } catch (e) {
      ctx.body = {
        code: 80001,
        msg: '删除失败'
      }
    }
  }

  /**
   * 查询菜单
   * @param ctx 
   * @param next 
   */
  public async get(ctx: Context, next: Next) {
    try {
      const res =  await permissionService.getPermissions()
      ctx.body = {
        code: 200,
        data: res[0]
      }
    } catch (e: any) {
      console.log(e)
      ctx.body = {
        code: 80001,
        msg: e.message || '系统异常'
      }
    }
  }
}

export default  new PermissionController()